<?php

namespace App\Console\Commands;

use App\Http\Controllers\LibApi\CdbtResourceController;
use App\Models\ResourceBusinessName;
use App\Models\ResourceCdbt;
use App\Models\ResourceTypeExternal;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

/**
 * 只有数据同步到数据库
 */
class CdbtMysqlData extends Command
{

    // 使用 命令行执行  php artisan command:CdbtMysqlData

    //  protected $data_sync_hour = 0; //0 表示不限制时间，全同步，其余表示 更改时间  单位小时
    protected $limit = 100; //每页限制条数
    protected $up_start_page = 1; //开始页，默认为 1

    protected $resource_business_id = 999; //资源商id


    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:CdbtMysqlData';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步自有资源数据到数据库';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $resourceBusinessNameModel = new  ResourceBusinessName();
        $resource_business_name_info = $resourceBusinessNameModel->where('id', $this->resource_business_id)->where('is_del', 1)->first();
        if (empty($resource_business_name_info)) {
            Log::channel('cdbtcmdlog')->debug('资源商不存在或已被删除');
            die;
        }

        try {
            //先同步数据
            $obj = new CdbtResourceController();
            $resourceTypeExternalModel = new ResourceTypeExternal();
            $resourceModel = new ResourceCdbt();
            //big_type_id 1 电子书  2 音频 3 视频
            for ($big_type_id = 1; $big_type_id < 4; $big_type_id++) {
                if (!in_array($big_type_id, [1])) {
                    continue; //只对接电子书
                }
                $total_data = $obj->getResourceList($big_type_id, 1, 1);
                if ($total_data['code'] == 200) {
                    $limit = $this->limit;
                    $total = $total_data['content']['total'];
                    $total_page = (int)ceil($total / $limit) + 1;

                    //获取所有数据和现在更新的数据做对比，如果没有则删除，有则不做处理
                    $data_unique_id_all = $resourceModel->select('guid', 'data_unique_id')->where('big_type_id', $big_type_id)->where('resource_business_id', $this->resource_business_id)->where('is_del', 1)->get()->toArray();
                    $data_unique_id_all = array_column($data_unique_id_all, 'guid', 'data_unique_id');

                    for ($i = 1; $i <= $total_page; $i++) {
                        $data = $obj->getResourceList($big_type_id, $i, $limit); //获取总数据量
                        if ($data['code'] == 200) {
                            $result_id = '';
                            foreach ($data['content']['data'] as $key => $val) {
                                //删除指定的值
                                unset($data_unique_id_all[$val['guid']]);

                                $type_id = $resourceTypeExternalModel->getTypeNameNoAdd(['name' => $val['type_name'], 'level' => null, 'resource_business_id' => $this->resource_business_id, 'big_type_id' => $big_type_id]);

                                $val['type_id'] = $type_id ?? null; //获取书籍小类
                                $val['big_type_id'] = $big_type_id; //大类  与资源管理系统一致
                                $val['data_unique_id'] = $val['guid']; //获取书籍小类
                                $result = $resourceModel->addData($val);
                                $result_id .= $result . '、';
                            }
                            Log::channel('cdbtcmdlog')->debug('全量同步上架数据，第 ' . $i . ' 页数据处理完毕: ' . $result_id);
                        } else {
                            //删除本地更新不存在的数据
                            if (!empty($data_unique_id_all)) {
                                $result_id = '';
                                foreach ($data_unique_id_all as $key => $val) {
                                    $del_id = $resourceModel->deleteData($key);
                                    $result_id .= $del_id . '、';
                                }
                                Log::channel('ytyscmdlog')->debug('删除本地更新不存在的数据，处理完毕: ' . $result_id);
                            }

                            Log::channel('cdbtcmdlog')->debug('全量同步上架数据处理完毕: 页数: ' . $i);
                            break;
                        }
                    }
                }
            }

            //获取数据下架列表
            $down_data = $obj->getDownResourceId(1, 99999);
            if ($down_data['code'] === 200) {
                //直接删除数据
                $result_id = '';
                foreach ($down_data['content'] as $key => $val) {
                    $del_id = $resourceModel->deleteData($val);
                    $result_id .= $del_id . '、';
                }

                Log::channel('cdbtcmdlog')->debug('全量同步下架数据，处理完毕: ' . $result_id);
            } else {
                Log::channel('cdbtcmdlog')->debug('暂无全量下架数据');
            }
            Log::channel('cdbtcmdlog')->debug('数据全部同步完成');
            // echo '数据全部同步完成';
            //更新同步时间
            $resourceBusinessNameModel->where('id', $this->resource_business_id)->update(['last_synch_time' => date('Y-m-d H:i:s')]);
        } catch (\Exception $e) {
            Log::channel('cdbtcmdlog')->debug('数据处理出现异常:' . $e->getMessage() . ';File:' . $e->getFile() . ';Line:' . $e->getLine() . ';');
        }
    }
}
